package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DIshController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto){
        log.info("添加菜品。。。。 dishDto:{}",dishDto.toString());
        //调用service层
        dishService.saveDishWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品管理分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        log.info("菜品管理分页查询： page: {} , pageSize: {} , name: {}",page,pageSize,name);
        //构建分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dtoPage = new Page<>();

        //将dishPage拷贝到dtoPage
        BeanUtils.copyProperties(dishPage,dtoPage,"records");

        //构建条件查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //进行分页查询
        dishService.page(dishPage,queryWrapper);

        //将dishPage中的records属性遍历出来
        //此时的records里面没有分类名称只有分类id
        List<Dish> records = dishPage.getRecords();
        //新建一个DishDto集合，用于最终返回的结果
        List<DishDto> dishDtoList = null;
        dishDtoList  =records.stream().map((item)->{
            //新建一个DishDto对象
            DishDto dishDto = new DishDto();
            //将dishDto中的属性补全
            //补全的属性没有categoryName
            BeanUtils.copyProperties(item,dishDto);
            //获取records中的categoryId
            Long categoryId = item.getCategoryId();
            //根据categoryId查询category数据库,获取category对象
            Category category = categoryService.getById(categoryId);
            //再将category对象中的name属性取出来
            String categoryName = category.getName();
            //将categoryName属性赋值给
            dishDto.setCategoryName(categoryName);
            //返回dishDto
            return dishDto;
        }).collect(Collectors.toList());

        //将dishDtoList集合赋值给dtoPage
        dtoPage.setRecords(dishDtoList);

        //返回dtoPage
        return R.success(dtoPage);
    }

    /**
     * 修改菜品时，用于菜品信息的回显
     * @param id 菜品id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDishDto(@PathVariable Long id){
        log.info("修改菜品时，菜品信息的回显。。。。id:{}",id);
        //调用service层
        DishDto dishDto = dishService.getByDishWithDisFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("修改菜品：dishDto：{}",dishDto.toString());
        //调用service层
        dishService.updateByDIshWithDishFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 修改菜品状态
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("修改菜品停售起售状态......ids:{} ,status:{}  ",ids,status);
        dishService.updateStatus(status,ids);
        return R.success("修改成功");
    }


    /**
     * 批量删除菜品信息
     * @return
     */
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids){
        log.info("批量删除菜品。。。。ids:{}",ids.toString());
        dishService.deleteByIds(ids);
        return R.success("删除菜品成功");
    }



    /**
     * 套餐管理中，新增套餐时候对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info("套餐管理，新增菜品数据  dish:{} ",dish.toString());
        //根据分类id查询菜品列表
        //构建查询构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        queryWrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item)->{
            //创建一个dishDto对象
            DishDto dishDto = new DishDto();
            //将list中的数据拷贝到dishDto中
            BeanUtils.copyProperties(item,dishDto);
            //dishDto中没有分类信息
            Long categoryId = item.getCategoryId();
            //根据分类id查询对象
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                //根据category查询分类名称
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //dishDto中没有对应的dishId
            Long DishId = item.getId();
            //根据DishId查询口味表
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishId!=null,DishFlavor::getDishId,DishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);
            //再将dishFlavors写入dishDto中
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }


}
